package what.the.fun.dao;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import what.the.fun.domain.AnswerResult;
import what.the.fun.domain.Result;
import what.the.fun.jdbc.AnswerResultRowMapper;
import what.the.fun.jdbc.ResultRowMapper;

public class ResultDAOImpl implements ResultDAO{

	@Autowired
	DataSource dataSource;
	JdbcTemplate jdbcTemplate;
	String sql;
	
	@Override
	public List<Result> getDataList() {
		sql = "call sp_result_GetAll ()";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		List<Result> list = new ArrayList<Result>();
		list = jdbcTemplate.query(sql, new ResultRowMapper());
		
		return list;
	}

	@Override
	public void insertData(Result data) {
		sql = "call sp_result_Insert (?, ?)";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		jdbcTemplate.update(sql, data.getSurveyId(), data.getUserId());
	}

	@Override
	public void updateData(Result data) {
		sql = "call sp_result_Update (?, ?, ?)";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		jdbcTemplate.update(sql, data.getSurveyId(), data.getUserId(), data.getResultId());
	}

	@Override
	public void deleteData(String id) {
		sql = "call sp_result_Delete (?)";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		jdbcTemplate.update(sql, id);
	}

	@Override
	public Result getData(String id) {
		sql = "call sp_result_GetById (?)";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		List<Result> list = new ArrayList<Result>();
		list = jdbcTemplate.query(sql, new ResultRowMapper(), id);
		
		return list.get(0);
	}

	@Override
	public List<AnswerResult> getAnswerResultListBySurveyId(String id) {
		sql = "call sp_result_GetAnswerResultListBySurveyId (?)";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		List<AnswerResult> list = new ArrayList<AnswerResult>();
		list = jdbcTemplate.query(sql, new AnswerResultRowMapper(), id);
		
		return list;
	}

	@Override
	public Result getLast() {
		sql = "call sp_result_GetLast()";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		List<Result> list = new ArrayList<Result>();
		list = jdbcTemplate.query(sql, new ResultRowMapper());
		
		return list.get(0);
	}

}
